extends Node2D

# 雪崩效果属性
@export var damage: int = 25  # 雪崩伤害
@export var direction: Vector2 = Vector2.DOWN  # 雪崩方向
@export var speed: float = 300.0  # 雪崩速度
@export var width: float = 300.0  # 雪崩宽度
@export var duration: float = 3.0  # 雪崩持续时间

var time_alive: float = 0.0
var has_damaged_player: bool = false
var player = null

func _ready():
	# 获取玩家引用
	player = get_tree().get_first_node_in_group("player")
	
	# 设置初始旋转
	rotation = direction.angle()
	
	# 设置粒子效果
	if has_node("CPUParticles2D"):
		$CPUParticles2D.emitting = true
		$CPUParticles2D.amount = 500
		$CPUParticles2D.lifetime = 1.0
		$CPUParticles2D.emission_shape = CPUParticles2D.EMISSION_SHAPE_RECTANGLE
		$CPUParticles2D.emission_rect_extents = Vector2(width / 2, 20)
		$CPUParticles2D.direction = Vector2(0, 1).rotated(rotation)
		$CPUParticles2D.spread = 10.0
		$CPUParticles2D.gravity = Vector2(0, 0)
		$CPUParticles2D.initial_velocity_min = speed * 0.8
		$CPUParticles2D.initial_velocity_max = speed * 1.2
		$CPUParticles2D.scale_amount = 3.0
		$CPUParticles2D.color = Color(1.0, 1.0, 1.0, 0.9)
	
	# 播放音效（如果有）
	if has_node("AudioStreamPlayer2D"):
		$AudioStreamPlayer2D.play()
	
	# 设置碰撞区域
	$Area2D/CollisionShape2D.shape.extents = Vector2(width / 2, 50)
	$Area2D.connect("body_entered", _on_body_entered)
	
	# 显示警告
	show_warning()

func _process(delta):
	# 更新生命周期
	time_alive += delta
	
	# 移动雪崩
	position += direction * speed * delta
	
	# 到达最大存活时间后消失
	if time_alive >= duration:
		queue_free()

func show_warning():
	# 创建警告效果
	var warning = Node2D.new()
	add_child(warning)
	
	# 添加警告标志
	var warning_sprite = Sprite2D.new()
	warning.add_child(warning_sprite)
	warning_sprite.texture = preload("res://asset/effects/warning.png")
	warning_sprite.position = Vector2(0, -100)  # 在雪崩前方显示
	
	# 闪烁效果
	var tween = create_tween()
	tween.set_loops(3)
	tween.tween_property(warning_sprite, "modulate:a", 0.0, 0.3)
	tween.tween_property(warning_sprite, "modulate:a", 1.0, 0.3)
	
	# 一秒后移除警告
	await get_tree().create_timer(1.0).timeout
	warning.queue_free()

func _on_body_entered(body):
	# 检查是否是玩家
	if body.is_in_group("player") and not has_damaged_player:
		has_damaged_player = true
		
		# 对玩家造成伤害
		body.take_damage(damage)
		
		# 击退效果
		var knockback_direction = direction
		if body.has_method("apply_knockback"):
			body.apply_knockback(knockback_direction * 300)
		
		# 冻结效果
		if body.has_method("apply_freeze_effect"):
			body.apply_freeze_effect(1.0)  # 冻结1秒
		elif body.has_method("apply_slow_effect"):
			body.apply_slow_effect(0.3, 3.0)  # 强力减速3秒
